package com.nyist.myticket.web.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * *过滤器的作用就是在请求来的时候拦截所有请求, 对其请求头进行校验, 以及 重新定义请求头里面的内容
 *
 * @author yangxiaogen
 * @date 2022/3/2 14:09
 */
@Slf4j
@Component
public class MyLogFilter implements Filter {

    String[] excludedUrl;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // excludedUrl = filterConfig.getInitParameter(SysConstant.SYS_EXCLUDED_URLS).split(",");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        log.info("过滤器被调用了........测试merge.....");

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;


        log.info("master新增数据..........");

        try {

            String requestURI = request.getRequestURI();

            if (isExcludedUrl(requestURI)) {
                log.info("日志过滤器被调用了...是不需要处理的请求地址...请求地址为: {}", request.getRequestURI());
                // 不进行后续的链的操作
                return;
            }

            log.info("日志过滤器被调用了.........请求地址为: {}", request.getRequestURI());
            log.info("日志过滤器被调用了.........请求ip为: {}", request.getRemoteHost());
            log.info("日志过滤器被调用了.........请求端口port为: {}", request.getRemotePort());
            chain.doFilter(request, response);
        } catch (Exception e) {
            log.error("=====> 调用过滤链异常,异常信息为: {}", e.getMessage());
        }
    }

    private boolean isExcludedUrl(String url) {
        if (excludedUrl == null || excludedUrl.length <= 0) {
            return false;
        }
        for (String ex : excludedUrl) {
            url = url.trim();
            ex = ex.trim();
            if (url.toLowerCase().matches(ex.toLowerCase().replace("*", ".*"))) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void destroy() {

    }
}
